from nonebot import on_command, CommandSession
import requests

@on_command('wh',aliases=('xh','小时天气','逐小时','小时'),only_to_me=False)
async def wh(session: CommandSession):
    city = session.get('city', prompt = '你想查询哪个城市?')
    weather_report = await get_weather_hourly_city(city)
    await session.send(weather_report)
    

@wh.args_parser
async def _(session: CommandSession):
    stripped_arg = session.current_arg_text.strip()
    
    if session.is_first_run:
        if stripped_arg:
            session.state['city'] = stripped_arg
        return
        
    if not stripped_arg:
        session.pause('不能为空,重新输入')
        
    session.state[session.current_key] = stripped_arg
    
    
async def get_weather_hourly_city(city: str) -> str:
    key = '851288973eec8ecf1320bd656b33453a'
    url = 'https://way.jd.com/he/freeweather?'

    #city = '南京'

    param = {
        'city': city,
        'appkey': key
    }
    req = requests.get(url,param)
    res = req.json()
    hour = res['result']['HeWeather5'][0]['hourly_forecast']
    
    ret = '查询: '+ city + '\n结果: '+res['result']['HeWeather5'][0]['basic']['city']+'\n'
    
    for i in hour:
        ret = ret + '时间: '+i['date']+'\nCTMP: '+i['cond']['txt']+i['tmp']+'℃'+'\n相对湿度: '+i['hum']+' 降水概率: '+i['pop']+'\n================\n'
        #return ret
    return ret
    
    
    
    